package app.jnsw.com.database.db;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;

import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.io.File;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.ParseException;

import app.jnsw.com.database.db.data.Law;
import app.jnsw.com.database.db.data.Law_type;
import app.jnsw.com.database.db.data.Mark;
import app.jnsw.com.database.db.data.User;


/**
 * Database helper class used to manage the creation and upgrading of your database. This class also usually provides
 * the DAOs used by the other classes.
 */
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

    // name of the database file for your application -- change to something appropriate for your app
    private static final String DATABASE_NAME = "AK.db";
    private static final int DATABASE_VERSION= 1;
    private static final String DATABASE_DIR = Environment.getExternalStorageDirectory().getPath() + "/AK/"; ;
    // any time you make changes to your database objects, you may have to increase the database version
    // the DAO object we use to access the SimpleData table

    private Dao<User, Integer> 用户Dao = null;
    private Dao<Mark, Integer> 书签Dao = null;
    private Dao<Law, Integer> 法律法规Dao = null;
    private Dao<Law_type, Integer> 法律类型Dao = null;



    public synchronized Dao<User, Integer> get用户Dao() throws SQLException {
        if (用户Dao == null)
            用户Dao = getDao(User.class);
        return 用户Dao;
    }
    public synchronized Dao<Mark, Integer> get书签Dao() throws SQLException {
        if (书签Dao == null)
            书签Dao = getDao(Mark.class);
        return 书签Dao;
    }
    public synchronized Dao<Law, Integer> get法律法规Dao() throws SQLException {
        if (法律法规Dao == null)
            法律法规Dao = getDao(Law.class);
        return 法律法规Dao;
    }
    public synchronized Dao<Law_type, Integer> get法律类型Dao() throws SQLException {
        if (法律类型Dao == null)
            法律类型Dao = getDao(Law_type.class);
        return 法律类型Dao;
    }



    public DatabaseHelper(Context context) {
//        super(context, DATABASE_DIR + DATABASE_NAME, null, DATABASE_VERSION, R.raw.xunjian_db_config);//自定义数据库文件位置
        super(context,  DATABASE_NAME, null, DATABASE_VERSION, R.raw.xunjian_db_config); //只写数据库名称 存放默认位置 随程序卸载而删除
    }

    /**
     * This is called when the database is first created. Usually you should call createTable statements here to create
     * the tables that will store your data.
     */
    @Override
    public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {

        Log.d("database Oncreate ","createDatabase ");
        try {
            if (!isFolderExists(DATABASE_DIR))
                throw new RuntimeException("data base can not creat");

            TableUtils.createTable(connectionSource, User.class);
            TableUtils.createTable(connectionSource, Mark.class);
//            TableUtils.createTable(connectionSource, Law.class);
            Log.d("createDatatable  ","createDatatables ------- ");

            try {
                generateTestData();
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } catch (SQLException e) {
            Log.e("DatabaseHelper", "Can't create database", e);
            throw new RuntimeException(e);
        }
    }
//创建测试数据
    private void generateTestData() throws ParseException {

        User user = new User();
        user.set登录名("abc");
        user.set密码("123");

        Mark mark = new Mark();
        mark.setID(1);
        mark.setName("书签1");
        mark.setX(new BigDecimal(3.951255649255562E7));
        mark.setY(new BigDecimal(3905427.911029636));
        mark.setScale(new BigDecimal(386200.22230222233));
        Mark mark1 = new Mark();
        mark1.setID(1);
        mark1.setName("书签2");
        mark1.setX(new BigDecimal(3.949003927973663E7));
        mark1.setY(new BigDecimal(3922719.8448731015));
        mark1.setScale(new BigDecimal(24082.26765077616));
        try {
            get用户Dao().create(user);
            get书签Dao().create(mark);
            get书签Dao().create(mark1);
            Log.d("DatabaseHelper","create");
        } catch (Exception e) {
            Log.d("DatabaseHelper","create"+ e.getMessage());
        }
    }
    /**
     * This is called when your application is upgraded and it has a higher version number. This allows you to adjust
     * the various data to match the new version number.
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {

        try {
            deleteFile(DATABASE_NAME);
            Log.i("DatabaseHelper", "onUpgrade");

            TableUtils.dropTable(connectionSource, User.class, true);
            TableUtils.dropTable(connectionSource, Mark.class, true);
//            TableUtils.dropTable(connectionSource, Law.class, true);

            onCreate(db, connectionSource);
        } catch (SQLException e) {

            Log.e("DatabaseHelper", "Can't drop databases", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * Returns the Database Access Object (DAO) for our SimpleData class. It will create it or just give the cached
     * value.
     */


    /**
     * Close the database connections and clear any cached DAOs.
     */
    @Override
    public void close() {
        super.close();
        用户Dao = null;
        书签Dao = null;
        法律法规Dao = null;

    }

    private void deleteFile(String path) {
        File file = new File(path);
        file.deleteOnExit();
    }

    boolean isFolderExists(String strFolder) {
        File file = new File(strFolder);
        if (!file.exists()) {
            if (file.mkdirs()) {
                return true;
            } else {
                return false;

            }
        }
        return true;

    }

    static DatabaseHelper instace;

    public static DatabaseHelper getInstace(Context context) {
        if (instace == null) {
            instace = OpenHelperManager.getHelper(context, DatabaseHelper.class);
            instace.getWritableDatabase();
        }
        return instace;
    }

}
